<?php

namespace handle\message\lib\manage\backups;

use handle\message\lib\factory\SingletonFactory;

class Backups
{
    /**
     * 文件路径名称
     * @var string
     */
    private string $filename;

    public function setRoomID(string $room_id): Backups
    {
        $this->filename = str_replace('\\', '/', DIRECTORY_SEPARATOR . date('YmdH') . DIRECTORY_SEPARATOR . $room_id);
        return $this;
    }

    /**
     * 保存数据
     * @param $instance
     * @return void
     */
    public function save($instance){
        putLog($this->filename . DIRECTORY_SEPARATOR . (strripos(get_class($instance), '\\') !== false ? substr(get_class($instance), strripos(get_class($instance), '\\') + 1) : get_class($instance)) . '.log', 'serialize:' . serialize($instance), '/backups', 0);  //备份不能作为日志连续存入，只能存入最新的，socket服务器重启后才能恢复备份数据
    }

    /**
     * 恢复数据
     * @return bool
     */
    public function restore(): bool
    {
        $flag = false;
        if(is_dir(BACKUP_PATH . $this->filename)){
            $manage = [
                'RoomManage' => 'room',
                'PlayerManage' => 'player',
                'ChessBoardManage' => 'board'
            ];
            //拿到这个目录下面的所有文件
            $files = scandir(BACKUP_PATH . $this->filename);
            foreach($files as $fileName){
                if($fileName == '.' or $fileName == '..')continue;
                $className = (substr($fileName, 0, strripos($fileName, '.')));
                $backupClass = file_get_contents(BACKUP_PATH . $this->filename . DIRECTORY_SEPARATOR . $fileName);
                if($className and !empty($manage[$className]) and !empty($backupClass)){
                    $backupClass = substr($backupClass, (strrpos($backupClass, 'serialize:') + strlen('serialize:')));
                    $manageClass = unserialize($backupClass);
                    if(!empty($manageClass)){
                        $flag = true;
                        SingletonFactory::getInstance()->makeInstances($manage[$className])->resetSingletonClass($manageClass);
                    }
                }
            }
        }
        return $flag;
    }

}